package com.smarttest.base

import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import com.smarttest.entity.NotifyEntity
import com.smarttest.ext.addDisposable
import com.smarttest.receiver.WifiReceiver
import com.smarttest.rxbus.RxBus
import dagger.android.AndroidInjection
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.HasFragmentInjector
import dagger.android.support.HasSupportFragmentInjector
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.error
import javax.inject.Inject

/**
 * HasFragmentInjector, HasSupportFragmentInjector用于支持fragment的注入
 * 说明：通用的activity注入类
 * Created by code_nil on 2018/1/30.
 * 君子自强不息
 */
abstract class BaseActivity : AppCompatActivity(), HasFragmentInjector, HasSupportFragmentInjector, AnkoLogger {

    @Inject
    lateinit var supportFragmentInjector: DispatchingAndroidInjector<Fragment>
    @Inject
    lateinit var frameworkFragmentInjector: DispatchingAndroidInjector<android.app.Fragment>
    lateinit var lifecycleObserver: ActivityLifecycleObserver

    private val wifiReceiver = WifiReceiver {
        responseWifiReceiver(it)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        //dagger2 androd扩展库
        AndroidInjection.inject(this)
        //创建lifecycle监听器
        lifecycleObserver = ActivityLifecycleObserver(this, wifiReceiver)
        //关联lifecycle
        lifecycle.addObserver(lifecycleObserver)
        super.onCreate(savedInstanceState)
    }

    /**
     * 必须实现的
     */
    abstract fun getContentId(): Int

    abstract fun responseWifiReceiver(code: Int)

    override fun fragmentInjector(): AndroidInjector<android.app.Fragment> = frameworkFragmentInjector
    override fun supportFragmentInjector(): AndroidInjector<Fragment> = supportFragmentInjector

    fun registeredRxBus(action: (any: NotifyEntity) -> Unit) {
        RxBus.getDefault()
                .toObservable(NotifyEntity::class.java)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    action(it)
                }, {
                    error { "${it.message}" }
                })
                .addDisposable(lifecycleObserver.disposables)
    }

    override fun onDestroy() {
        super.onDestroy()
        lifecycle.removeObserver(lifecycleObserver)
    }
}